#include <stdio.h>
#include <event.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <string.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <arpa/inet.h>

#define PORT 8888

struct event_base *main_base;
static const char MSG[]="hello word!";


void accept_handle(const int sfd, const short event , void *arg)
{
	printf("accept handle \n");
	struct sockaddr_in addr;
	socklen_t addrlen  = sizeof(addr);
	int fd =accept(sfd, (struct sockaddr *)&addr , &addrlen);
	struct bufferevent *buf_ev;
	buf_ev = bufferevent_new(fd,NULL,NULL,NULL,NULL);
	buf_ev->wm_read.high =4096;
	printf("event write \n");
	bufferevent_write(buf_ev , MSG , strlen(MSG));
	
}


int main(){
	
	main_base = event_init();
	if(main_base)
		printf("init event successfully! \n");
	int listenfd;
	listenfd =socket(AF_INET,SOCK_STREAM ,IPPROTO_TCP);
	struct sockaddr_in server;
	bzero(&server, sizeof(server));
	server.sin_family= AF_INET;
	server.sin_addr.s_addr=htonl(INADDR_ANY);
	server.sin_port=htons(PORT);
	
	int ret = bind(listenfd , (struct sockaddr *)&server ,sizeof(server));

	if(ret == -1)
	{
		printf("fail to bind");
		return -1;
	}
	listen(listenfd , 5);
	
	printf("server is listening \n");
	
	int flags =fcntl(listenfd , F_GETFL);
	flags |= O_NONBLOCK;
	fcntl(listenfd, F_SETFL,flags);
	struct event ev;
	
	event_set(&ev,listenfd,EV_READ|EV_PERSIST,accept_handle , (void *)&ev);
	event_add(&ev , NULL);
	event_base_loop(main_base, 0 );
	

	return 0;


}
